<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-header-actions">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/workflow-templates' }">工作流模板管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: `/workflow-templates/${templateId}/versions` }">
            版本历史
          </el-breadcrumb-item>
          <el-breadcrumb-item>版本对比</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="action-buttons">
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
        </div>
      </div>
    </div>

    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span class="card-title">版本对比</span>
          <div class="version-selector">
            <el-select v-model="selectedVersion1" placeholder="选择版本1" @change="handleVersionChange">
              <el-option
                v-for="v in versions"
                :key="v.version"
                :label="`v${v.version}`"
                :value="v.version"
              />
            </el-select>
            <span style="margin: 0 10px;">vs</span>
            <el-select v-model="selectedVersion2" placeholder="选择版本2" @change="handleVersionChange">
              <el-option
                v-for="v in versions"
                :key="v.version"
                :label="`v${v.version}`"
                :value="v.version"
              />
            </el-select>
            <el-button type="primary" @click="handleCompare" :disabled="!canCompare">
              对比
            </el-button>
          </div>
        </div>
      </template>

      <div v-if="diffData" class="diff-container">
        <!-- 基本信息对比 -->
        <el-descriptions title="基本信息对比" :column="2" border>
          <el-descriptions-item label="版本号">
            <span class="version-tag">v{{ diffData.version1.version }}</span>
            <el-icon style="margin: 0 8px;"><Right /></el-icon>
            <span class="version-tag">v{{ diffData.version2.version }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="变更说明">
            {{ diffData.version2.change_log || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            <div class="diff-text">
              <div class="old-text">
                <el-tag type="danger" size="small">旧:</el-tag>
                {{ diffData.version1.description || '无' }}
              </div>
              <div class="new-text">
                <el-tag type="success" size="small">新:</el-tag>
                {{ diffData.version2.description || '无' }}
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 节点变化统计 -->
        <el-descriptions title="变化统计" :column="3" border style="margin-top: 20px;">
          <el-descriptions-item label="新增节点">
            <el-tag type="success">{{ diffData.changes.added.length }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="删除节点">
            <el-tag type="danger">{{ diffData.changes.removed.length }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="修改节点">
            <el-tag type="warning">{{ diffData.changes.modified.length }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 详细变化列表 -->
        <div style="margin-top: 20px;">
          <h3>详细变化</h3>

          <!-- 新增节点 -->
          <el-collapse v-if="diffData.changes.added.length > 0">
            <el-collapse-item title="新增节点" name="added">
              <el-table :data="diffData.changes.added" stripe>
                <el-table-column prop="id" label="节点ID" width="150" />
                <el-table-column prop="type" label="节点类型" width="150" />
                <el-table-column prop="name" label="节点名称" min-width="200" />
                <el-table-column label="配置">
                  <template #default="{ row }">
                    <pre class="config-json">{{ JSON.stringify(row.config, null, 2) }}</pre>
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>
          </el-collapse>

          <!-- 删除节点 -->
          <el-collapse v-if="diffData.changes.removed.length > 0" style="margin-top: 10px;">
            <el-collapse-item title="删除节点" name="removed">
              <el-table :data="diffData.changes.removed" stripe>
                <el-table-column prop="id" label="节点ID" width="150" />
                <el-table-column prop="type" label="节点类型" width="150" />
                <el-table-column prop="name" label="节点名称" min-width="200" />
                <el-table-column label="配置">
                  <template #default="{ row }">
                    <pre class="config-json">{{ JSON.stringify(row.config, null, 2) }}</pre>
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>
          </el-collapse>

          <!-- 修改节点 -->
          <el-collapse v-if="diffData.changes.modified.length > 0" style="margin-top: 10px;">
            <el-collapse-item title="修改节点" name="modified">
              <el-table :data="diffData.changes.modified" stripe>
                <el-table-column prop="id" label="节点ID" width="150" />
                <el-table-column prop="type" label="节点类型" width="150" />
                <el-table-column label="修改详情" min-width="400">
                  <template #default="{ row }">
                    <div class="modification-detail">
                      <div v-if="row.name_changed">
                        <strong>名称:</strong>
                        <span class="old-value">{{ row.old.name }}</span>
                        <el-icon><Right /></el-icon>
                        <span class="new-value">{{ row.new.name }}</span>
                      </div>
                      <div v-if="row.config_changed">
                        <strong>配置已变更</strong>
                      </div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>

      <el-empty v-else description="请选择两个版本进行对比" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useWorkflowTemplateStore } from '@/stores/workflowTemplate'

const router = useRouter()
const route = useRoute()
const templateStore = useWorkflowTemplateStore()

const templateId = ref(parseInt(route.params.id))
const loading = ref(false)
const versions = ref([])
const selectedVersion1 = ref(null)
const selectedVersion2 = ref(null)
const diffData = ref(null)

const canCompare = computed(() => {
  return selectedVersion1.value !== null &&
         selectedVersion2.value !== null &&
         selectedVersion1.value !== selectedVersion2.value
})

const fetchVersions = async () => {
  try {
    await templateStore.fetchVersionHistory(templateId.value)
    versions.value = templateStore.versionHistory
  } catch (error) {
    console.error('获取版本列表失败:', error)
    ElMessage.error('获取版本列表失败')
  }
}

const handleVersionChange = () => {
  diffData.value = null
}

// 计算两个版本之间的变化
const calculateChanges = (version1, version2) => {
  const nodes1 = version1.workflow_definition?.nodes || []
  const nodes2 = version2.workflow_definition?.nodes || []

  // 创建节点ID映射
  const nodes1Map = new Map(nodes1.map(n => [n.id, n]))
  const nodes2Map = new Map(nodes2.map(n => [n.id, n]))

  const added = []
  const removed = []
  const modified = []

  // 查找新增和修改的节点
  nodes2.forEach(node2 => {
    const node1 = nodes1Map.get(node2.id)
    if (!node1) {
      // 新增节点
      added.push(node2)
    } else {
      // 检查是否修改
      const nameChanged = node1.name !== node2.name
      const configChanged = JSON.stringify(node1.config) !== JSON.stringify(node2.config)

      if (nameChanged || configChanged) {
        modified.push({
          id: node2.id,
          type: node2.type,
          name_changed: nameChanged,
          config_changed: configChanged,
          old: node1,
          new: node2
        })
      }
    }
  })

  // 查找删除的节点
  nodes1.forEach(node1 => {
    if (!nodes2Map.has(node1.id)) {
      removed.push(node1)
    }
  })

  return { added, removed, modified }
}

const handleCompare = async () => {
  if (!canCompare.value) {
    ElMessage.warning('请选择两个不同的版本进行对比')
    return
  }

  loading.value = true
  try {
    const data = await templateStore.fetchVersionDiff(
      templateId.value,
      selectedVersion1.value,
      selectedVersion2.value
    )

    // 计算节点变化
    const changes = calculateChanges(data.version1, data.version2)

    // 组装完整的 diffData
    diffData.value = {
      ...data,
      changes
    }
  } catch (error) {
    console.error('对比版本失败:', error)
    ElMessage.error('对比版本失败')
  } finally {
    loading.value = false
  }
}

const handleBack = () => {
  router.push(`/workflow-templates/${templateId.value}/versions`)
}

onMounted(async () => {
  await fetchVersions()

  // 从URL参数中读取默认版本
  if (route.query.version1) {
    selectedVersion1.value = parseInt(route.query.version1)
  }
  if (route.query.version2) {
    selectedVersion2.value = parseInt(route.query.version2)
  }

  // 如果提供了默认版本，自动进行对比
  if (canCompare.value) {
    handleCompare()
  }
})
</script>

<style lang="scss" scoped>
.page-header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.version-selector {
  display: flex;
  align-items: center;
  gap: 10px;
}

.diff-container {
  padding: 20px 0;
}

.diff-text {
  display: flex;
  flex-direction: column;
  gap: 10px;

  .old-text,
  .new-text {
    display: flex;
    align-items: center;
    gap: 10px;
  }
}

.version-tag {
  padding: 2px 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  font-weight: 600;
}

.config-json {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.6;
  max-height: 200px;
  overflow: auto;
}

.modification-detail {
  display: flex;
  flex-direction: column;
  gap: 8px;

  .old-value {
    color: #f56c6c;
    text-decoration: line-through;
    margin: 0 5px;
  }

  .new-value {
    color: #67c23a;
    font-weight: 600;
    margin: 0 5px;
  }
}
</style>
